package com.jxsd.edu.cn.struts2.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import com.jxsd.edu.cn.struts2.models.Attributes;
import com.jxsd.edu.cn.struts2.models.Category;
import com.jxsd.edu.cn.struts2.models.PubMsgview;
import com.jxsd.edu.cn.struts2.models.PublishGoodAttribute;
import com.jxsd.edu.cn.struts2.models.SmallCatagory;
import com.jxsd.edu.cn.struts2.serviceImpl.AttributeServiceImpl;
import com.jxsd.edu.cn.struts2.serviceImpl.CatagoryServiceImpl;
import com.jxsd.edu.cn.struts2.serviceImpl.IndexServiceImpl;
import com.jxsd.edu.cn.struts2.serviceImpl.PubMsgServiceImpl;
import com.jxsd.edu.cn.struts2.serviceImpl.SmallServiceImpl;
import com.jxsd.edu.cn.struts2.services.AttributeService;
import com.jxsd.edu.cn.struts2.services.CatagoryService;
import com.jxsd.edu.cn.struts2.services.IndexService;
import com.jxsd.edu.cn.struts2.services.PubMsgService;
import com.jxsd.edu.cn.struts2.services.SmallService;
import com.jxsd.edu.cn.tools.BookInfoCrawler;
import com.jxsd.edu.cn.tools.BookUrlCrawler;
import com.jxsd.edu.cn.tools.Page;
import com.jxsd.edu.cn.tools.PageBean;
import com.jxsd.edu.cn.tools.QueryNewlyPublishId;
import com.jxsd.edu.cn.tools.StringTool;
import com.opensymphony.xwork2.ActionContext;



/**
 * 发布物品信息记录
 * */
public class PublishAction 
{
   /**
    * 物品发布记录
    * */
	private   PubMsgview  pubMsg=new   PubMsgview();
	//一级类别信息
 	private     List<Category>   list;
 	//类别属性列表
 	private     List<Attributes>  attris;
 	//文件
 	private     File          cover;
    private   String        coverContentType;
    private   String        coverFileName;
    //保存路径
	private   String       savePath;
	
	//列表数据
	private   Page<PubMsgview>   page;
	//分页列表数据请求器
	private   PageBean<PubMsgview>  pagebean=new  PageBean<PubMsgview>();
	//列表数据
	
	private   List<PubMsgview>  msgs;
	//二级列表之二级类别数据
	private    List<SmallCatagory>  smalls;
	//一级类别编号
	private    String   catagoryId;
	//二级类别编号
	private   String    smallId;
	
	//分页需要使用到的URL
	private   String   url;
	
	//IndexService
    private     CatagoryService   cataService;
    //PubMsgService
    private   PubMsgService    pubService;
    //AttributeService
    private   AttributeService  attriService;
 	//IndexService
    private   IndexService    indexService;
    //smallService
    private  SmallService   smallService;
    
	//构造方法
	public  PublishAction()
	{
		cataService=new  CatagoryServiceImpl();
		pubService=new   PubMsgServiceImpl();
		attriService=new  AttributeServiceImpl();
		indexService=new   IndexServiceImpl();
		smallService=new   SmallServiceImpl();
	}
	
	/**
	 * 发布一条物品信息记录
	 * */	
	public  String  publishMsg()
	{
		//获取导航信息
		getCatagories();
		
		String  fosPath=null;
		try {
			fosPath=doUpload();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		pubMsg.setCover(fosPath);
		//取得当前物品发布记录可用的编号
		int  publishID=QueryNewlyPublishId.getNewlyPublishId()+1;
		pubMsg.setPublishID(publishID);
		//设置当前用户id
		int  userId=(Integer)ActionContext.getContext().getSession().get("userId");
		
		pubMsg.setAuthor(userId);
		
		//获取用户填写的物品属性信息
		HttpServletRequest  request=ServletActionContext.getRequest();
		
		String  smallName=null;
		String  catagoryName=null;
		try {
			smallName= new  String(pubMsg.getSmallName().getBytes("ISO8859-1"),"UTF-8");
			catagoryName=new  String(pubMsg.getCatagoryName().getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		attris=attriService.getAttributes(smallName, catagoryName);
		
		
		
		
		List<PublishGoodAttribute>  fromattrList=new  ArrayList<PublishGoodAttribute>();
		for(Attributes  attr:attris)
		{
			String  attriName=attr.getAttributeName();
			String  attriValue=request.getParameter(attriName);
			PublishGoodAttribute  goodAttri=new  PublishGoodAttribute();
			goodAttri.setAttributeName(attriName);
			goodAttri.setAttributeValue(attriValue);
			fromattrList.add(goodAttri);
		}
		pubMsg.setAttributes(fromattrList);
		
		//发布物品信息
		pubService.pubMsg(pubMsg);
		
		return  "third";
	}
	
	/**
	 * 获取postMessage1页面
	 * */
	public  String  forPubFirstView()
	{
		//获取导航信息
		list=indexService.getAllCatagory();
		return  "first";
	}
	
	/**
	 * 获取postMessage2页面
	 * @throws Exception 
	 * */
	public  String  forPubSecondView()
	{
		//获取导航信息
		getCatagories();
		//取得发布需要的属性数据
		String smallName=null;
		String  catagoryName=null;
		try {
		smallName= new  String(pubMsg.getSmallName().getBytes("ISO8859-1"),"UTF-8");
		catagoryName=new  String(pubMsg.getCatagoryName().getBytes("ISO8859-1"),"UTF-8");
		
		
		pubMsg.setSmallName(smallName);
		pubMsg.setCatagoryName(catagoryName);
		
		
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		}
		System.out.println("catagoryName："+pubMsg.getCatagoryName());
		
		attris=attriService.getAttributes(smallName, catagoryName);
		
		return  "second";
	}
	
	/**
	 * 获取爬虫需要的数据
	 * @throws IOException 
	 * */
	public  void  querycralData() throws IOException
	{
		HttpServletResponse response=ServletActionContext.getResponse();
 		response.setContentType("text/plain");
 		response.setCharacterEncoding("UTF-8");
		
		
		
		//获取类型信息
		HttpServletRequest request=ServletActionContext.getRequest();
		String  data=request.getParameter("data");
		
		System.out.println("***********************************data:"+data);
		
		
		//获取爬虫需要的数据
		String  attriData=getAttributeData(data);
		
		System.out.println("***********************************attriData:"+attriData);
		
		PrintWriter  writer=response.getWriter();
		

 		writer.write(attriData);
 		writer.flush();
 		writer.close();
	}
	
	/**
	 * 获取一条发布信息
	 * */
	public  String  queryPubMsg()
	{
		
		//获取导航信息
		getCatagories();
		
		System.out.println("**************************************");
		System.out.println("publishId:"+pubMsg.getPublishID());
		System.out.println("publishId:"+pubMsg.getPublishID());
		System.out.println("**************************************");
		
		
		pubMsg=pubService.getPubMsg(Integer.toString(pubMsg.getPublishID()));
		
		System.out.println(pubMsg.getCatagoryName());
		System.out.println(pubMsg.getImage());
		
		return  "detail";
	}
	/**
	 * 获取二级发布页面列表
	 * */
	public  String  querySecondList()
	{
		//获取导航信息
		getCatagories();
		//获取某个一级类别的二级类别信息
		smalls=smallService.getCataSmalls(catagoryId);
		//获取客户的区域性信息
		String  cityName=(String)ActionContext.getContext().getSession().get("cityName");
		if(null==cityName||cityName.length()==0)
		{
			cityName="南昌";
		}
		if(page!=null)
		{
			pagebean.setCurrentPage(page.getCurrent_page());
		}
		page=pubService.getSmallPubMsgTitles(cityName,smallId, pagebean);
		//获取本城最新发布的物品信息记录
		 queryNewlyMsgs();
		 //获取当前Action的完整路径
		 this.setUrl("user/publish_querySecondList.action?smallId="+smallId+"&catagoryId="+catagoryId);
		
		return  "secondlist";
	}
	
	
	/**
	 * 获取一级类别来的二级列表
	 * */
	public  String  queryCataSecondList()
	{
		//获取导航
		list=cataService.getAllCatagory();
		//获取某个一级类别的二级类别信息
		smalls=smallService.getCataSmalls(catagoryId);
		
		//获取客户的区域性信息
		String  cityName=(String)ActionContext.getContext().getSession().get("cityName");
		if(null==cityName||cityName.length()==0)
		{
			cityName="南昌";
		}
		if(page!=null)
		{
			pagebean.setCurrentPage(page.getCurrent_page());
		}
		
		//获取分页数据
		page=pubService.getCataPubMsgTitles(cityName,catagoryId, pagebean);
		//获取本城最新发布的物品信息记录
		 queryNewlyMsgs();
		 
		 //获取当前的URl
		 this.setUrl("user/publish_queryCataSecondList.action?catagoryId="+catagoryId);
		 
		
		return  "secondlist";
	}
	/**
	 * 获取修改物品信息发布记录页面
	 * */
	public   String  queryUpdatePage()
	{
		//获取导航信息
		getCatagories();
		//获取数据
		pubMsg=pubService.getPubMsg(Integer.toString(pubMsg.getPublishID()));
		return  "correctpubmsg";
	}
	/**
	 * 处理修改请求
	 * */
	public  String  updatePubMsg()
	{
		//获取导航信息
		getCatagories();
		
		String  fosPath=null;
		try {
			fosPath=doUpload();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		pubMsg.setCover(fosPath);
		
		//获取用户填写的物品属性信息
		HttpServletRequest  request=ServletActionContext.getRequest();
		
		String  smallName=null;
		String  catagoryName=null;
		try {
			smallName= new  String(pubMsg.getSmallName().getBytes("ISO8859-1"),"UTF-8");
			catagoryName=new  String(pubMsg.getCatagoryName().getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		attris=attriService.getAttributes(smallName, catagoryName);
		
		List<PublishGoodAttribute>  fromattrList=new  ArrayList<PublishGoodAttribute>();
		for(Attributes  attr:attris)
		{
			String  attriName=attr.getAttributeName();
			String  attriValue=request.getParameter(attriName);
			PublishGoodAttribute  goodAttri=new  PublishGoodAttribute();
			goodAttri.setAttributeName(attriName);
			goodAttri.setAttributeValue(attriValue);
			fromattrList.add(goodAttri);
		}
		pubMsg.setAttributes(fromattrList);
		
		//更新物品记录
		pubService.updatePubMsg(pubMsg);
		
		return  "correctsuccess";
	}
	/**
	 * 删除一条物品记录
	 * */
	public  String  deletePubMsg()
	{
		pubService.deletePubMsg(Integer.toString(pubMsg.getPublishID()));
		
		return "detele";
	}
	
	/**
	 * 获取本城最新发布的物品信息记录
	 * */
	private   void   queryNewlyMsgs()
	{
		//获取客户的区域性信息
		String  cityName=(String)ActionContext.getContext().getSession().get("cityName");
		if(null==cityName||cityName.length()==0)
		{
			cityName="南昌";
		}
		msgs=pubService.queryNewlyMsgs(cityName);
	}
	
	
	/**
	    * hander  the  upload  file
	 * @throws FileNotFoundException 
	    * */
	   private  String  doUpload() throws Exception
	   {
		   String  fosPath=null;
		   
		   if(null==getCoverFileName())
		   {
			   return  "portrait/dasheng.jpg";
		   }
		   
		// 对于上传文件的存放地址来建立一个输出流
			fosPath=getSavePath()+"/"+ System.currentTimeMillis()
				+ getCoverFileName().substring(getCoverFileName().lastIndexOf("."),
						getCoverFileName().length());
			
			String path = ServletActionContext.getServletContext()     
	                .getRealPath("/")+fosPath;
			
		   FileOutputStream fos = new FileOutputStream(path);
		   FileInputStream fis = new FileInputStream( getCover());
		   byte[] buffer = new byte[1024];
		   int len = 0;
		   while ((len = fis.read(buffer)) > 0)
		   {
		    fos.write(buffer , 0 , len);
		   }
		   
		   fis.close();
		   fos.close();
		   
		   return  fosPath;
	   }
	   
	   
	
	/**
     * 获取导航信息
     * */
    private  void  getCatagories()
    {
    	list=indexService.getAllCatagory();
    }
    /**
     * 获取爬虫信息
     * */
    private  String    getAttributeData(String  data)
    {
    	BookInfoCrawler  crawler=new  BookInfoCrawler();
    	BookUrlCrawler   urlcrawler=new  BookUrlCrawler();
    	
    	String  url=urlcrawler.crawling("http://search.winxuan.com/search?keyword="+data);
    	
    	HashMap<String,String>  map=new  HashMap<String,String>();
		map=crawler.crawling(url);
		
		AttributeService  service=new  AttributeServiceImpl();
		List<Attributes>   list=service.getAttributes("计算机网络", "书籍");
		String  s="";
		for(Attributes  attri:list)
		{
			String  name=StringTool.trimer(attri.getAttributeName());
			String  value=map.get(name);
//			System.out.println(value);
			if(value!=null)
			{
			s+=value;
			s+="*#*";
			}
		}
		s=s.substring(0, s.lastIndexOf("*#*")+3);
		
		s+=map.get("describes");
		
		return  s;
    }

	public PubMsgview getPubMsg() {
		return pubMsg;
	}
	
	public void setPubMsg(PubMsgview pubMsg) {
		this.pubMsg = pubMsg;
	}



	public List<Category> getList() {
		return list;
	}

	public void setList(List<Category> list) {
		this.list = list;
	}

	public List<Attributes> getAttris() {
		return attris;
	}

	public void setAttris(List<Attributes> attris) {
		this.attris = attris;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

   public File getCover() {
		return cover;
	}

	public void setCover(File cover) {
		this.cover = cover;
	}

	public String getCoverContentType() {
		return coverContentType;
	}

	public void setCoverContentType(String coverContentType) {
		this.coverContentType = coverContentType;
	}

	public String getCoverFileName() {
		return coverFileName;
	}

	public void setCoverFileName(String coverFileName) {
		this.coverFileName = coverFileName;
	}

	public Page<PubMsgview> getPage() {
		return page;
	}

	public void setPage(Page<PubMsgview> page) {
		this.page = page;
	}

	public PageBean<PubMsgview> getPagebean() {
		return pagebean;
	}

	public void setPagebean(PageBean<PubMsgview> pagebean) {
		this.pagebean = pagebean;
	}

	public List<SmallCatagory> getSmalls() {
		return smalls;
	}

	public void setSmalls(List<SmallCatagory> smalls) {
		this.smalls = smalls;
	}
	
	public String getCatagoryId() {
		return catagoryId;
	}

	public void setCatagoryId(String catagoryId) {
		this.catagoryId = catagoryId;
	}

	public String getSmallId() {
		return smallId;
	}

	public void setSmallId(String smallId) {
		this.smallId = smallId;
	}

	public List<PubMsgview> getMsgs() {
		return msgs;
	}

	public void setMsgs(List<PubMsgview> msgs) {
		this.msgs = msgs;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

}
